package com.zqc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqc.dto.DishDto;
import com.zqc.entity.Dish;
import com.zqc.entity.DishFlavor;
import com.zqc.mapper.DishMapper;
import com.zqc.service.DishFlavorService;
import com.zqc.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    public DishFlavorService dishFlavorService;

    /**
     * 添加菜品和菜品口味，操作两张表
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveDishAndFlavor(DishDto dishDto) {
        // 1 保存菜品
        this.save(dishDto);
        // 2 保存菜品口味
        // 给菜品口味实体设置菜品id

        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
        dishFlavorList = dishFlavorList.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    /**
     * 查询单个菜品和菜品的口味
     * @param id
     * @return
     */
    @Override
    public DishDto getDishAndFlavors(Long id) {
        // 返回的数据需要包含菜品口味，依旧需要进行对象的转换
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        List<DishFlavor> flavors = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, id));
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    /**
     * 更新菜品个菜品口味
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateDishAndFlavors(DishDto dishDto) {
        // 1 更新菜品
        this.updateById(dishDto);

        // 2 删除原来的口味，dish_flavor表的删除操作
        dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId,dishDto.getId()));

        // 3更新口味
        List<DishFlavor> dishFlavors = dishDto.getFlavors().stream().map(item -> {
            // 将口味设置菜品的id
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.updateBatchById(dishFlavors);

    }


}
